package com.chenl.provider.DEMOS.Mysql.Mybatis.自动装配;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class MateMetaObjectHandler implements MetaObjectHandler {
    //使用mp,如果实现添加的操作，这个方法执行   (属性名称，值，元数据对象)
    @Override
    public void insertFill(MetaObject metaObject) {
        // 先判断是否存在该字段
        boolean createTimeFLag = metaObject.hasSetter("createTime") && metaObject.hasGetter("createTime");
        boolean updateTimeFlag = metaObject.hasSetter("updateTime") && metaObject.hasGetter("updateTime");
        boolean modifyTimeFlag = metaObject.hasSetter("modifyTime") && metaObject.hasGetter("modifyTime");
        Object createTime = this.getFieldValByName("createTime", metaObject);
        Object updateTime = this.getFieldValByName("updateTime", metaObject);
        Object modifyTime = this.getFieldValByName("modifyTime", metaObject);
        if (createTimeFLag && createTime == null) {
            //createTime要和实体类的字段对应上
            this.setFieldValByName("createTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), metaObject);
        }
        if (updateTimeFlag && updateTime == null) {
            this.setFieldValByName("updateTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), metaObject);
        }
        if (modifyTimeFlag && modifyTime == null) {
            this.setFieldValByName("modifyTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), metaObject);
        }
    }

    //使用mp。实现一个修改的操作，这个方法执行
    @Override
    public void updateFill(MetaObject metaObject) {
        // 先判断是否存在该字段
        boolean updateTimeFlag = metaObject.hasSetter("updateTime") && metaObject.hasGetter("updateTime");
        boolean modifyTimeFlag = metaObject.hasSetter("modifyTime") && metaObject.hasGetter("modifyTime");
        Object updateTime = this.getFieldValByName("updateTime", metaObject);
        Object modifyTime = this.getFieldValByName("modifyTime", metaObject);
        if (updateTimeFlag && updateTime == null) {
            this.setFieldValByName("updateTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), metaObject);
        }
        if (modifyTimeFlag && modifyTime == null) {
            this.setFieldValByName("modifyTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), metaObject);
        }
    }
}